package com.jielin.handling.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author : longdeng.zhang@gmail.com
 * @date：2015-3-24 下午12:08:08
 * 类说明：
 */
public class StringUtil {

    /**
     * 生成UUID
     *
     * @param value
     * @return
     */
    public static String generatorUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 空字符串验证
     *
     * @param value
     * @return
     */
    public static boolean isEmpty(String value) {
        if (value == null || value.trim().length() == 0 || value.equals("null") || value.equals("undefined")) {
            return true;
        }
        return false;
    }

    /**
     * 空对象与空字符串验证
     *
     * @param obj
     * @param strings
     * @return
     */
    public static boolean isEmptyObJ(Object obj, String... strings) {
        if (obj == null) {
            return true;
        }
        for (String str : strings) {
            if (isEmpty(str)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 邮箱验证
     *
     * @param value
     * @return
     */
    public static boolean isEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 手机验证
     *
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) {
        boolean flag = false;
        try {
            Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18([0-3]|[5-9]))|(17([0]|[6]|[7])))\\d{8})$");
            Matcher matcher = regex.matcher(phone);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 方法功能说明：  String转MD5
     * 创建：2016-9-21 by 刘新海
     * 修改：日期 by 修改者
     * 修改内容：
     *
     * @return String
     * @throws
     * @参数： @param str
     * @参数： @return
     * @参数： @throws NoSuchAlgorithmException
     * @参数： @throws UnsupportedEncodingException
     */
    public static String StringToMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest(str.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder(bytes.length << 1);
        for (int i = 0; i < bytes.length; i++) {
            sb.append(Character.forDigit((bytes[i] >> 4) & 0xf, 16));
            sb.append(Character.forDigit(bytes[i] & 0xf, 16));
        }
        return sb.toString();
    }

    /**
     * 生成随机文件名，防止上传文件后文件名重复
     *
     * @return
     */
    public static String generateRandomFilename() {
        String RandomFilename = "";
        Random rand = new Random();//生成随机数
        int random = rand.nextInt();

        Calendar calCurrent = Calendar.getInstance();
        int intDay = calCurrent.get(Calendar.DATE);
        int intMonth = calCurrent.get(Calendar.MONTH) + 1;
        int intYear = calCurrent.get(Calendar.YEAR);
        String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
                String.valueOf(intDay) + "_";

        RandomFilename = now + String.valueOf(random > 0 ? random : (-1) * random);

        return RandomFilename;
    }

    /**
     * Mysql检索时，转换特殊字符
     *
     * @param s
     * @return
     */
    public static String escapeMysqlChars(String s) {
        if (isEmpty(s)) {
            return s;
        }
        List<Character> newChar = new ArrayList<>();
        //查询字符串一般不会太长，挨个遍历也花费不了多少时间
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // These characters are part of the query syntax and must be escaped
            if (c == '%' || c == '_') {
                newChar.add('/');
            }
            newChar.add(c);
        }
        return newChar.stream()
                .map(String::valueOf)
                .collect(Collectors.joining());
    }

    /**
     * 图片文件后缀验证
     *
     * @param fileType 文件后缀
     * @return
     */
    public static boolean isPHOTO(String fileType) {
        if (fileType != null && fileType.matches(
                "^(.jpg|.png|.JPG|.PNG|.jpeg|.JPEG|.bmp|.BMP|.svg|.SVG|.ico|.ICO|.tif|.TIF)$")) {
            return true;
        }
        return false;
    }

    /**
     * 视频文件后缀验证
     *
     * @param fileType 文件后缀
     * @return
     */
    public static boolean isVIDEO(String fileType) {
        if (fileType != null && fileType
                .matches("^(.mp4|.MP4|.mov|.MOV|.AVI|.avi|.mkv|.MKV|.flv|.FLY|.rmvb|.RMVB|.wmv|.WMV)$")) {
            return true;
        }
        return false;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(StringUtil.isPhone("18210323496"));
        System.out.println(StringUtil.isPhone("17010323496"));
        System.out.println(StringUtil.isPhone("17610323496"));
        System.out.println(StringUtil.isPhone("17210323496"));
        System.out.println(StringUtil.isPhone("182103234966"));
        System.out.println(StringUtil.isPhone("18210323A496"));
        System.out.println(StringUtil.isEmail("longdeng0000@163.com"));
        System.out.println(StringUtil.isEmail("longdeng0000@"));
    }

}
